<template>
  <el-button size="small" type="primary" @click="handleAdd()">
    新增
  </el-button>
  <el-card>
    <!--查询条件-->
    <el-form :inline="true" :model="condition" class="demo-form-inline">
      <el-form-item label="案例标题：">
        <el-input v-model="condition.title" placeholder="请输入案例标题" clearable />
      </el-form-item>
      <el-form-item label="作者ID：">
        <el-input v-model="condition.author_id" placeholder="请输入作者ID" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchNews()">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="case_id" label="案例ID" width="80" />
      <el-table-column prop="title" label="案例标题" />
      <el-table-column prop="author_id" label="作者ID" width="100" />
      <el-table-column prop="tool_used" label="使用工具" />
      <el-table-column prop="views_count" label="浏览次数" width="100" />
      <el-table-column prop="likes_count" label="点赞次数" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          {{ formatStatus(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="160" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row)">
            查看
          </el-button>
          <el-button size="small" type="primary" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-popconfirm title="您确定要删除吗?" @confirm="handleRemove(scope.row.case_id)">
            <template #reference>
              <el-button size="small" type="warning">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="demo-pagination-block">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[6, 7, 8, 9]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 查看对话框 -->
    <el-dialog v-model="viewDialogVisible" title="案例详情" width="50%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="案例ID">{{ currentNews.case_id }}</el-descriptions-item>
        <el-descriptions-item label="案例标题">{{ currentNews.title }}</el-descriptions-item>
        <el-descriptions-item label="作者ID">{{ currentNews.author_id }}</el-descriptions-item>
        <el-descriptions-item label="案例图片">
          <img
              v-if="currentNews.thumbnail_url"
              :src="currentNews.thumbnail_url"
              alt="案例缩略图"
              style="max-width: 300px; max-height: 200px"
          >
          <span v-else>无图片</span>
        </el-descriptions-item>
        <el-descriptions-item label="使用工具">{{ currentNews.tool_used }}</el-descriptions-item>
        <el-descriptions-item label="浏览次数">{{ currentNews.views_count }}</el-descriptions-item>
        <el-descriptions-item label="点赞次数">{{ currentNews.likes_count }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ formatStatus(currentNews.status) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentNews.created_at }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentNews.updated_at }}</el-descriptions-item>
        <el-descriptions-item label="案例正文">{{ currentNews.content }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" :title="editDialogTitle" width="50%">
      <el-form :model="currentNews" label-width="80px">
        <el-form-item label="案例ID">
          <el-input v-model="currentNews.case_id" disabled />
        </el-form-item>
        <el-form-item label="案例标题">
          <el-input v-model="currentNews.title" />
        </el-form-item>
        <el-form-item label="作者ID">
          <el-input v-model="currentNews.author_id" />
        </el-form-item>
        <el-form-item label="案例图片">
          <el-input v-model="currentNews.thumbnail_url" placeholder="图片URL" />
        </el-form-item>
        <el-form-item label="使用工具">
          <el-input v-model="currentNews.tool_used" />
        </el-form-item>
        <el-form-item label="浏览次数">
          <el-input v-model="currentNews.views_count" type="number" />
        </el-form-item>
        <el-form-item label="点赞次数">
          <el-input v-model="currentNews.likes_count" type="number" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentNews.status" placeholder="请选择">
            <el-option label="草稿" value="draft" />
            <el-option label="发布" value="published" />
            <el-option label="下架" value="unpublished" />
          </el-select>
        </el-form-item>
        <el-form-item label="案例正文">
          <el-input v-model="currentNews.content" type="textarea" rows="5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axiosObject from '@/main.js';

// 表格数据
const tableData = ref([])
// 对话框状态
const viewDialogVisible = ref(false)
const editDialogTitle = ref("")
const editDialogVisible = ref(false)
const currentNews = ref({})

// 查询条件
const condition = ref({ "title": "", "author_id": "" })

// 分页参数
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)

// 字段映射：后端小驼峰 → 前端下划线（适配表格显示）
const formatBackendData = (item) => {
  return {
    case_id: item.caseId || '无',
    title: item.title || '无标题',
    author_id: item.authorId || '无',
    thumbnail_url: item.thumbnailUrl || '',
    tool_used: item.toolUsed || '未填写',
    views_count: item.viewsCount || 0,
    likes_count: item.likesCount || 0,
    status: item.status || 'draft',
    created_at: item.createdAt || '未记录',
    updated_at: item.updatedAt || '未记录',
    content: item.content || '无内容'
  }
}

// 格式化状态显示
const formatStatus = (status) => {
  const statusMap = {
    'draft': '草稿',
    'published': '发布',
    'unpublished': '下架'
  }
  return statusMap[status] || '未知'
}

// 分页-切换当前页
const handleCurrentChange = () => {
  findNewsList();
}

// 分页-切换每页条数
const handleSizeChange = () => {
  currentPage.value = 1; // 切换页大小时重置到第一页
  findNewsList();
}

// 条件查询
const searchNews = () => {
  currentPage.value = 1; // 查询时重置到第一页
  findNewsList();
}

// 查看案例详情
const handleView = (row) => {
  currentNews.value = { ...row }
  viewDialogVisible.value = true
}

// 新增案例
const handleAdd = () => {
  editDialogTitle.value = "添加案例";
  currentNews.value = {
    case_id: '自动生成',
    views_count: 0,
    likes_count: 0,
    status: 'draft'
  };
  editDialogVisible.value = true;
}

// 编辑案例
const handleEdit = (row) => {
  editDialogTitle.value = "编辑案例";
  currentNews.value = { ...row }
  editDialogVisible.value = true
}

// 删除案例
const handleRemove = async (id) => {
  try {
    await axiosObject.delete("news/" + id);
    // 若删除的是当前页最后一条且不是第一页，切换到上一页
    if (tableData.value.length === 1 && currentPage.value > 1) {
      currentPage.value--;
    }
    await findNewsList();
  } catch (error) {
    console.error("删除失败：", error);
    alert("删除失败，请稍后重试");
  }
}

// 字段映射：前端下划线 → 后端小驼峰（适配接口提交）
const formatSubmitData = (data) => {
  return {
    caseId: data.case_id === '无' || data.case_id === '自动生成' ? null : data.case_id,
    title: data.title || '',
    authorId: data.author_id === '无' ? null : data.author_id,
    thumbnailUrl: data.thumbnail_url || '',
    toolUsed: data.tool_used === '未填写' ? '' : data.tool_used,
    viewsCount: Number(data.views_count) || 0,
    likesCount: Number(data.likes_count) || 0,
    status: data.status || 'draft',
    content: data.content === '无内容' ? '' : data.content
  }
}

// 保存新增/编辑数据
const handleSave = async () => {
  try {
    const submitData = formatSubmitData(currentNews.value);
    // 根据是否有caseId判断新增/编辑
    if (submitData.caseId) {
      await axiosObject.put("news", submitData);
    } else {
      await axiosObject.post("news", submitData);
    }
    await findNewsList();
    editDialogVisible.value = false;
    alert("操作成功");
  } catch (error) {
    console.error("保存失败：", error);
    alert("保存失败，请稍后重试");
  }
}

// 获取案例列表（核心修复：正确解析后端数据）
const findNewsList = async () => {
  try {
    const payload = {
      ...condition.value,
      page: currentPage.value,
      size: pageSize.value
    };

    const result = await axiosObject.post('/news/list', payload);
    console.log("后端原始数据：", result.data);

    // 正确解析后端返回结构：resultData → list（数据数组）、total（总条数）
    const resultData = result.data.resultData || {};
    const backendList = resultData.list || []; // 提取真正的表格数据数组
    total.value = resultData.total || 0; // 提取总条数，适配分页

    // 转换字段格式后赋值给表格
    tableData.value = backendList.map(item => formatBackendData(item));
  } catch (error) {
    console.error("获取列表失败：", error);
    alert("加载数据失败，请刷新页面重试");
  }
};

// 页面加载时初始化数据
onMounted(() => {
  findNewsList();
})
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.demo-pagination-block {
  margin-top: 15px;
  text-align: right;
}
</style>